{% extends 'extends/nav_front_all_.html' %}

{% block main %}
    <!-- 卡片容器 -->
    <div class="container py-4">
        <div class="card">
            <div class="card-body">
                <form id="filterForm">
                    <div class="row">
                        <div class="col-md-5">
                            <label for="startDate" class="form-label">开始时间</label>
                            <input type="text" class="form-control datepicker" id="startDate" placeholder="选择开始时间">
                        </div>
                        <div class="col-md-5">
                            <label for="endDate" class="form-label">结束时间</label>
                            <input type="text" class="form-control datepicker" id="endDate" placeholder="选择结束时间">
                        </div>
                        <div class="col-md-2 d-flex align-items-end">
                            <button type="submit" class="btn btn-primary w-100" id="but">筛选</button>
                        </div>
                    </div>
                </form>

                <div class="mt-4">
                    <canvas id="myChart"></canvas>
                </div>
            </div>
        </div>
    </div>

    <script>
        function getFormattedDate(daysAgo) {
            return new Date(Date.now() - daysAgo * 864e5).toLocaleString('zh-CN', { hour12: false }).replace(/\//g, '-');
        }


        let chartInstance = null;

 async function loadData(url) {
    // 获取表单中的 startDate 和 endDate
    const startDate = document.getElementById('startDate').value;
    const endDate = document.getElementById('endDate').value;

    await Fetch(url, 'get', {
        'start': startDate,  // 获取的startDate
        'end': endDate       // 获取的endDate
    }, res => {
        if (res.status === 'success') {
            const { likes, get_likes, follows, fans } = res.data;

            const allData = [];
            likes.forEach(item => {
                allData.push({ time: item.time, likes: 1, get_likes: 0, follows: 0, fans: 0 });
            });
            get_likes.forEach(item => {
                allData.push({ time: item.time, likes: 0, get_likes: 1, follows: 0, fans: 0 });
            });
            follows.forEach(item => {
                allData.push({ time: item.time, likes: 0, get_likes: 0, follows: 1, fans: 0 });
            });
            fans.forEach(item => {
                allData.push({ time: item.time, likes: 0, get_likes: 0, follows: 0, fans: 1 });
            });


            // 按时间排序
            allData.sort((a, b) => new Date(a.time) - new Date(b.time));

            // 自动设置开始结束时间
            const firstDate = allData[0].time.substring(0, 10);
            const lastDate = allData[allData.length - 1].time.substring(0, 10);

            const start = startDate ? startDate : firstDate;
            const end = endDate ? endDate : lastDate;

            // 生成时间轴
            const labels = [];
            let currentDate = new Date(start);
            const endDateObj = new Date(end);
            while (currentDate <= endDateObj) {
                labels.push(currentDate.toISOString().substring(0, 10));
                currentDate.setDate(currentDate.getDate() + 1); // 加一天
            }

            // 按天累加数据
            const likesData = [];
            const getLikesData = [];
            const followsData = [];
            const fansData = [];

            let totalLikes = 0, totalGetLikes = 0, totalFollows = 0, totalFans = 0;
            labels.forEach(label => {
                allData.forEach(item => {
                    if (item.time.substring(0, 10) === label) {
                        totalLikes += item.likes;
                        totalGetLikes += item.get_likes;
                        totalFollows += item.follows;
                        totalFans += item.fans;
                    }
                });
                likesData.push(totalLikes);
                getLikesData.push(totalGetLikes);
                followsData.push(totalFollows);
                fansData.push(totalFans);
            });

            // 如果存在旧图表实例，销毁它
            if (chartInstance) {
                chartInstance.destroy();
            }

            const ctx = document.getElementById('myChart').getContext('2d');
            chartInstance = new Chart(ctx, {
                type: 'line',
                data: {
                    labels: labels,
                    datasets: [
                        {
                            label: '累计点赞数',
                            data: likesData,
                            borderColor: 'rgba(75, 192, 192, 1)',
                            borderWidth: 2,
                            fill: false
                        },
                        {
                            label: '累计获得点赞数',
                            data: getLikesData,
                            borderColor: 'rgba(153, 102, 255, 1)',
                            borderWidth: 2,
                            fill: false
                        },
                        {
                            label: '累计关注数',
                            data: followsData,
                            borderColor: 'rgba(255, 159, 64, 1)',
                            borderWidth: 2,
                            fill: false
                        },
                        {
                            label: '累计粉丝数',
                            data: fansData,
                            borderColor: 'rgba(255, 99, 132, 1)',
                            borderWidth: 2,
                            fill: false
                        }
                    ]
                },
                options: {
                    responsive: true,
                    scales: {
                        x: {
                            title: {
                                display: true,
                                text: '日期'
                            }
                        },
                        y: {
                            title: {
                                display: true,
                                text: '累计'
                            },
                            ticks: {
                                stepSize: 1
                            },
                            beginAtZero: true
                        }
                    }
                }

            });
        }
    });
}




        onUrlsReady(async urls => {
            flatpickr("#startDate", {
                locale: "zh",                  // 设置为中文
                enableTime: true,              // 启用时间选择
                dateFormat: "Y-m-d H:i:S",     // 设置日期格式
                time_24hr: true,               // 使用24小时制
                defaultDate: getFormattedDate(7),  // start为7天前
            });

            flatpickr("#endDate", {
                locale: "zh",                  // 设置为中文
                enableTime: true,              // 启用时间选择
                dateFormat: "Y-m-d H:i:S",     // 设置日期格式
                time_24hr: true,               // 使用24小时制
                defaultDate: getFormattedDate(0),  // end为当前时间
            });
            Event_('but', 'click', async event => {
                await loadData(urls.info.data)
            })

            await loadData(urls.info.data)
        })
    </script>

{% endblock %}
